from PySide6.QtWidgets import (
    QDialog, QVBoxLayout, QTextEdit, QPushButton, QHBoxLayout, QWidget, QApplication
)
from PySide6.QtGui import QFontMetrics, QTextOption
from PySide6.QtCore import Qt, QTimer


class DialogWidget:
    """弹窗"""

    @staticmethod
    def show_scrollable(parent: QWidget, title: str, text: str, is_error=False):
        """根据内容真实宽高自动调整窗口大小"""
        dlg = QDialog(parent)
        dlg.setWindowTitle(title)
        dlg.setWindowFlags(Qt.Dialog | Qt.WindowCloseButtonHint | Qt.WindowStaysOnTopHint)

        layout = QVBoxLayout(dlg)

        # ---- 文本框 ----
        text_edit = QTextEdit()
        text_edit.setReadOnly(True)
        text_edit.setWordWrapMode(QTextOption.NoWrap)
        text_edit.setPlainText(text)
        text_edit.setStyleSheet(f"""
            QTextEdit {{
                background-color: #fafafa;
                border: 1px solid #dcdfe6;
                border-radius: 6px;
                padding: 6px;
                color: {'#e74c3c' if is_error else '#333'};
                font-family: 'Consolas';
                font-size: 12px;
            }}
        """)
        layout.addWidget(text_edit)

        # ---- 底部按钮 ----
        btn_layout = QHBoxLayout()
        btn_layout.addStretch()
        ok_btn = QPushButton("确定")
        ok_btn.clicked.connect(dlg.accept)
        btn_layout.addWidget(ok_btn)
        layout.addLayout(btn_layout)

        # ---- 自动计算内容宽高 ----
        def adjust_size():
            fm = QFontMetrics(text_edit.font())
            lines = text.splitlines() or [""]

            # 每行的像素宽度
            max_line_width = max((fm.horizontalAdvance(line) for line in lines), default=0)
            text_height = fm.height() * len(lines)

            # 加上边距、标题栏、高度余量
            width = max_line_width + 60
            height = text_height + 80  # 含边距、按钮、标题栏

            # 获取屏幕尺寸，防止超出屏幕
            screen_rect = QApplication.primaryScreen().availableGeometry()
            width = min(width, screen_rect.width() - 100)
            height = min(height, screen_rect.height() - 100)

            dlg.resize(width, height)

        # 延迟执行调整，等待 QTextEdit 渲染完成
        QTimer.singleShot(0, adjust_size)

        dlg.exec()

    @staticmethod
    def info(parent: QWidget, title: str, text: str):
        DialogWidget.show_scrollable(parent, title, text)

    @staticmethod
    def error(parent: QWidget, title: str, text: str):
        DialogWidget.show_scrollable(parent, title, text, is_error=True)
